//
//  AnswerTableViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/6/17.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import SVProgressHUD
class AnswerTableViewController: UITableViewController,AnswerTableViewCellDelegate, RGFadeDelegate{
    
    var rgFadeView: RGFadeView?
    var modelList: [AnswerModel]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    var requistID: String?
    var docID: String?
    var page = 0
    override func viewDidLoad() {
        super.viewDidLoad()

        publicMethod.setHUDStyle()
        self.tableView.estimatedRowHeight = 182
        
        self.tableView.rowHeight = UITableViewAutomaticDimension
        publicMethod.hiddleExtendCellForTableView(self.tableView)
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(AnswerTableViewController.requestInfo))
         self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(AnswerTableViewController.nextRequestInfo))
        self.tableView.mj_header.beginRefreshing()
    }
    
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
        super.viewWillDisappear(animated)
    }
    override func viewWillAppear(animated: Bool) {
        self.tabBarController?.tabBar.hidden = false
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK:AnswerTableViewCellDelegate
    
    func shareBtnSelected(id: String){
        
        let shareParames = NSMutableDictionary()
        let url = ""
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.modelList![0].id,
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(nil, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: self.showAlert("分享成功")
            case SSDKResponseState.Fail:
                self.showAlert("分享失败")// print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  self.showAlert("分享取消")//print("分享取消")
                
            default:
                break
            }
        }

    }
    //MARK: showSuccessAlert
    func showAlert(message: String){
        let alertView = UIAlertView(title: "", message: message, delegate: nil, cancelButtonTitle: "确定" )
        
        alertView.show()
    }

    func zanBtnSelected(id: String){
        self.clickLike(id)
    }
    func commentBtnSelected(id: String, docid: String){
        self.requistID = id
        self.docID = docid
        if (rgFadeView == nil) {
            rgFadeView = RGFadeView.init(frame: kScreen_frame)
            //rgFadeView?.docid = newsDetailModel?.docid
            rgFadeView?.delegate = self
            self.view.addSubview(rgFadeView!)
        }
        rgFadeView?.msgTextView.becomeFirstResponder()
        

        
    }
    //MARK:RGFadeViewDelegate
    func sendBtnDown(text: String) {
        
        let jsonData = ["commentid": self.requistID!, "message": text, "docid":self.docID!]
         //jsonData = ["docid": id, "message": text, "commentid":self.modelList!.id, "reply":self.requistID]
        DataTool.sendComment(jsonData,type: "", completionHandler: { (isSuccess) -> Void in
            if isSuccess {
                SVProgressHUD.showSuccessWithStatus("回复成功")
               
                self.requestInfo()
            } else {
                SVProgressHUD.showErrorWithStatus("回复失败")
               
            }
        })
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        
        if let count = modelList?.count {
            return count
        } else {
            return 0
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("AnswerTableViewCell", forIndexPath: indexPath) as! AnswerTableViewCell

        // Configure the cell...
        cell.model = self.modelList![indexPath.row]
        cell.delegate = self
        
        if modelList![indexPath.row].isdianzan == true{
            cell.zanBtn.setBackgroundImage(UIImage(named: "zan_selected"), forState: UIControlState.Normal)
        } else {
            
            cell.zanBtn.setBackgroundImage(UIImage(named: "zan"), forState: UIControlState.Normal)
        }
        
        cell.conmenBtnClicked = { [weak self]() in
            self?.commentBtnSelected(String(self!.modelList![indexPath.row].id), docid: String(self!.modelList![indexPath.row].docid))
            
        }
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let cell = tableView.dequeueReusableCellWithIdentifier("AnswerTableViewCell") as! AnswerTableViewCell
        let cellInfo = self.modelList![indexPath.row]
        cell.setCellContentWithCellInfo((cellInfo.comment?.message)!, andCommenText: cellInfo.message)
        
        return cell.cellHeight!

    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
       tableView.deselectRowAtIndexPath(indexPath, animated: true)
      
        let sb = UIStoryboard.init(name: "NewsList", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("ReplyVC") as! ReplyVC
            
            vc.id = (modelList![indexPath.row].comment?.id)!
            vc.type = "行业"
        self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
        self.hidesBottomBarWhenPushed = false
       
        
    }

    //MARK:networking
    
    /**
     下拉刷新，加载最新数据
     */
    func requestInfo() {
        self.tableView.mj_footer.resetNoMoreData()
        self.page = 0
        DataTool.loadMessageAnswerData({ (newsArray) -> Void in
            self.tableView.mj_header.endRefreshing()
            guard let newDataes = newsArray else {
                return
            }
            self.modelList = newDataes
        })
    }
    /**
     上拉刷新，加载最新数据
     */
    func nextRequestInfo() {
        self.page += 1
        let urlStr = String(format: "%@message/reply/fenye/\(self.page)",BaseUrl)
        DataTool.loadNextMessageAnswerData(String(self.page),urlStr: urlStr,completionHandler: { (newsArray) -> Void in
            
            guard let newDataes = newsArray else {
                return
            }
            if newDataes.count == 0 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer.endRefreshing()
                self.modelList! += newDataes
            }
            
        })
        
    }
    func clickLike(id: String){
        
        DataTool.supposeComment(Int(id)!, type: "行业" , completionHandler: { (isSuccess) -> Void in
            if isSuccess {
                 let cell = self.tableView.dequeueReusableCellWithIdentifier("AnswerTableViewCell") as! AnswerTableViewCell
                cell.zanBtn.setImage(UIImage(named: "zan_selected"), forState: UIControlState.Normal)
            } else {
                SVProgressHUD.showErrorWithStatus("点赞失败")
                
            }
        })

    }
    
}
